<template>
	<div :class="className">
		<Chart :cdata="cdata" />
	</div>
</template>

<script>
import Chart from './chart';

export default {
    components: {
        Chart,
    },
    props: {
        className: { type: String, default: '' },
        isMock: { type: Boolean, default: false },
    },
    data() {
        return {
            dataTimer: null,
            cdata: [],
        };
    },
    mounted() {
        if (this.isMock) {
            this.mock(1);
        } else {
            this.getData();
        }

        this.setTimer();
    },
    beforeUnmount() {
        if (this.dataTimer) {
            clearInterval(this.dataTimer);
            this.dataTimer = null;
        }
    },
    methods: {
        setTimer() {
            let i = 1;
            this.dataTimer = setInterval(async () => {
                if (this.isMock) {
                    this.mock(i++);
                } else {
                    await this.getData();
                }
            }, this.isMock ? 2000 : 60000); // 一分钟
        },
        mock(start) {
            const data = [];

            for (let index = 0; index < 24; index++) {
                const v1 = Math.round(Math.random() * 60);
                const v2 = Math.round(Math.random() * 10);

                const time = (start + index) % 24;
                data.push({ time: `${time}:00`, okCount: v1, ngCount: v2 });
            }

            this.cdata = data;
        },
        async getData() {
            try {
                const resp = await this.$API.reportproductivity.hourly.get();
                if (resp.code === 200) {
                    this.cdata = resp.data ?? [];
                }
            } catch {
                console.warn("[productivity-hourly] 无响应数据");
            }
        }
    },
}
</script>

<style lang="scss" scoped></style>
